// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespafeeder;

import com.yahoo.clientmetrics.MessageTypeMetricSet;
import com.yahoo.clientmetrics.RouteMetricSet;
import com.yahoo.concurrent.Timer;
import com.yahoo.metrics.Metric;
import com.yahoo.metrics.MetricSet;
import com.yahoo.metrics.MetricVisitor;

import java.io.PrintStream;

/**
 * Class that takes progress from the feed and prints to a stream.
 */
public class BenchmarkProgressPrinter implements RouteMetricSet.ProgressCallback {
    private final long startTime;
    private final Timer timer;
    private final PrintStream output;

    public BenchmarkProgressPrinter(Timer timer, PrintStream output) {
        this.timer = timer;
        this.output = output;
        this.startTime = timer.milliTime();
    }

    class PrintVisitor extends MetricVisitor {
        private final PrintStream out;

        PrintVisitor(PrintStream out) {
            this.out = out;
        }

        @Override
        public boolean visitMetricSet(MetricSet set, boolean autoGenerated) {
            if (set instanceof MessageTypeMetricSet && set.getName().equals("total")) {
                Metric m = set.getMetric("latency");
                Metric count = set.getMetric("count");
                Metric err = set.getMetric("errors.total");

                long okCount = 0, errCount = 0, minLatency = 0, maxLatency = 0, avgLatency = 0;

                if (m != null) {
                    minLatency = m.getLongValue("min");
                    maxLatency = m.getLongValue("max");
                    avgLatency = m.getLongValue("average");
                }
                if (count != null) {
                    okCount = count.getLongValue("count");
                }

                if (err != null) {
                    errCount = err.getLongValue("count");
                }
                long timeUsed = timer.milliTime() - startTime;
                out.println(timeUsed + ", " + okCount + ", " + errCount + ", " + minLatency + ", " + maxLatency + ", " + avgLatency);
            }
            return true;
        }
    }

    @Override
    public void onProgress(RouteMetricSet metrics) {
	//metrics.visit(new PrintVisitor(output), false);
    }

    @Override
    public void done(RouteMetricSet metrics) {
        try {
		output.println("# Time used, num ok, num error, min latency, max latency, average latency");
            metrics.visit(new PrintVisitor(output), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
